package com.huawei.crm.web.controller;

import com.github.pagehelper.PageInfo;
import com.huawei.crm.domain.Role;
import com.huawei.crm.query.QueryObject;
import com.huawei.crm.service.IPermissionService;
import com.huawei.crm.service.IRoleService;
import com.huawei.crm.util.JsonResult;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService service;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @RequiresPermissions(value = {"角色列表","role:list"}, logical = Logical.OR)
    public String list(Model model, QueryObject qo){
        PageInfo<Role> pageInfo = service.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "role/list";
    }

    @RequestMapping("/delete")
    @RequiresPermissions(value = {"角色删除","role:delete"}, logical = Logical.OR)
    @ResponseBody
    public JsonResult delete(Long id) {
        JsonResult result = new JsonResult();
        try {
            if (id != null) {
                service.delete(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("亲,删除失败");
        }
        return result;
    }

    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"角色更改或保存","role:saveOrUpdate"}, logical = Logical.OR)
    public String saveOrUpdate(Role e,Long[] permissionIds){
        service.saveOrUpdate(e, permissionIds);
        return "redirect:/role/list";
    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"角色编辑","role:input"}, logical = Logical.OR)
    public String input(Model model,Long id){
        if(id != null){
            Role r = service.get(id);
            model.addAttribute("r",r);
        }
        //查询高级查询表单中需要的部门信息
        model.addAttribute("permissions", permissionService.listAll());
        return "role/input";
    }
}
